<!--  -->
<template>
  <div class="contentbox flex-col dictionary-box">
    <el-card class="dictionary-margin flex-col">
      <div class="taskmain flex-col">
        <div>
          <el-descriptions
            class="dictionary-margin"
            title="代码模板"
            size="medium"
            :column="1"
            :colon="false"
          >
            <el-descriptions-item>
              <div class="taskview-top">
                <span>模板分类名称：</span>
                <el-select
                  placeholder="请选择"
                  v-model="inputTempleteClassValue"
                  clearable
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
                <span>模板名称：</span>
                <el-input placeholder="请输入" v-model="inputTempleteValue">
                </el-input>
                <el-button type="primary" @click="selectTemplateClass"
                  >搜索</el-button
                >
                <el-button type="primary" @click="addTempleteClass"
                  >添加分类</el-button
                >
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="taskmain flex-col">
          <el-table
            v-loading="loading"
            :data="tableData"
            :row-key="templateRowkey"
            :expand-row-keys="templateExpandRowkey"
            tooltip-effect="dark"
            height="100%"
            :default-expand-all="codeExpand"
            :row-class-name="getRowClass"
            ref="templateModel"
          >
            <el-table-column type="expand">
              <template slot-scope="props">
                <div v-if="props.row.Children.length > 0">
                  <el-table
                    row-key="TemplateName"
                    :data="props.row.Children"
                    :show-header="true"
                    max-height="400px"
                  >
                    <el-table-column width="70"></el-table-column>
                    <el-table-column
                      type="index"
                      label="序号"
                      show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                      prop="TemplateName"
                      label="模板名称"
                    ></el-table-column>
                    <el-table-column
                      prop="Description"
                      label="说明"
                    ></el-table-column>
                    <el-table-column
                      prop="CreateTime"
                      label="创建时间"
                    ></el-table-column>
                    <el-table-column label="操作">
                      <template slot-scope="scope">
                        <el-button
                          type="text"
                          @click="handleTemplateDetail(scope.$index, scope.row)"
                          >内容详情</el-button
                        >
                        <el-button
                          type="text"
                          @click="handleTemplateEdit(scope.$index, scope.row)"
                          >修改</el-button
                        >
                        <el-button
                          type="text"
                          @click="handleTemplateDelete(scope.$index, scope.row)"
                          >删除</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :index="table_index"
              label="序号"
              type="index"
              width="120"
            ></el-table-column>
            <el-table-column
              prop="TemplateName"
              label="模板分类名称"
            ></el-table-column>
            <el-table-column
              prop="CreateTime"
              label="创建时间"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="handleAdd(scope.$index, scope.row)"
                  >新增模板</el-button
                >
                <el-button
                  type="text"
                  @click="handleEdit(scope.$index, scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="text"
                  @click="handleDelete(scope.$index, scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-pagination
          background
          layout="->,total,prev, pager, next,sizes, jumper"
          :current-page.sync="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          :total="totalTableDataSum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
      <!-- 新增、修改代码模板分类Dialog -->
      <el-dialog
        destroy-on-close
        :visible.sync="classAddOrEditDialogVisible"
        width="30%"
        @close="
          () => {
            this.classDialogModel.categoryName = '';
          }
        "
      >
        <span slot="title" style="text-align: center"
          >{{ dialogAddOrEditName }}
          <el-divider></el-divider>
        </span>
        <el-form
          label-width="200px"
          :model="classDialogModel"
          ref="classAddRef"
        >
          <el-form-item
            label="模板分类名称："
            prop="categoryName"
            :rules="[
              {
                required: true,
                message: '模板分类名称不可为空',
                trigger: ['blur', 'change'],
              },
            ]"
          >
            <el-input
              style="width: 50%"
              v-model="classDialogModel.categoryName"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" style="text-align: center">
          <el-divider></el-divider>
          <div>
            <el-button
              @click="
                () => {
                  classAddOrEditDialogVisible = false;
                  this.classDialogModel.categoryName = '';
                }
              "
              >取 消</el-button
            >
            <el-button
              type="primary"
              @click="confirmTempleteClassAddOrEdit('classAddRef')"
              >确 定</el-button
            >
          </div>
        </span>
      </el-dialog>

      <!-- 新增、修改代码模板Dialog -->
      <el-dialog
        destroy-on-close
        :visible.sync="templateAddOrEditDialogVisible"
        width="30%"
        @close="
          () => {
            this.templateDialogModel = {
              categoryId: '',
              templateName: '',
              descriptions: '',
            };
          }
        "
      >
        <span slot="title" style="text-align: center"
          >{{ templateDialogAddOrEditName }}
          <el-divider></el-divider>
        </span>
        <el-form
          label-width="200px"
          :model="templateDialogModel"
          ref="templateAddRef"
        >
          <el-form-item
            label="模板名称："
            prop="templateName"
            :rules="[
              {
                required: true,
                message: '模板名称不可为空',
                trigger: ['blur', 'change'],
              },
            ]"
          >
            <el-input
              style="width: 50%"
              v-model="templateDialogModel.templateName"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="模板分类："
            prop="categoryId"
            :rules="[
              {
                required: true,
                message: '模板分类不可为空',
                trigger: ['blur', 'change'],
              },
              {
                validator: (rule, value, callback) => {
                  if (value === null) {
                    callback(new Error('模板分类不可为空'));
                  } else {
                    callback();
                  }
                },
                trigger: ['blur', 'change'],
              },
            ]"
          >
            <el-select
              style="width: 50%"
              v-model="templateDialogModel.categoryId"
              disabled
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="说明："
            prop="descriptions"
            :rules="[
              {
                required: true,
                message: '说明不可为空',
                trigger: ['blur', 'change'],
              },
            ]"
          >
            <el-input
              type="textarea"
              :rows="4"
              style="width: 50%"
              v-model="templateDialogModel.descriptions"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" style="text-align: center">
          <el-divider></el-divider>
          <div>
            <el-button
              @click="
                () => {
                  templateAddOrEditDialogVisible = false;
                  //this.classDialogModel.categoryName = '';
                }
              "
              >取 消</el-button
            >
            <el-button
              type="primary"
              @click="confirmTempleteAddOrEdit('templateAddRef')"
              >确 定</el-button
            >
          </div>
        </span>
      </el-dialog>

      <!--代码模板内容详情Dialog -->
      <el-dialog destroy-on-close :visible.sync="templateContentDialogVisible">
        <span slot="title"
          >内容详情
          <el-divider></el-divider>
          <span
            style="
              font-weight: bold;
              font-size: 16px;
              color: #333;
              text-align: center;
              width: 100%;
            "
          >
            {{ templateDetail.templateName }}
          </span>
        </span>
        <div>
          <codemirror
            v-model="templateDetail.templateContent"
            :options="OptionCodeInput"
          ></codemirror>
        </div>
        <span slot="footer" class="dialog-footer" style="text-align: center">
          <el-divider></el-divider>
          <div>
            <el-button
              @click="
                () => {
                  templateContentDialogVisible = false;
                  this.templateDetail.templateContent = '';
                  //this.classDialogModel.categoryName = '';
                }
              "
              >取 消</el-button
            >
            <el-button type="primary" @click="confirmSaveTemplateContent()"
              >保 存</el-button
            >
          </div>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import $http from "@/utils/apiHelper";
// #region 覆盖scrollbar样式功能
import "codemirror/addon/scroll/simplescrollbars.css";
import "codemirror/addon/scroll/simplescrollbars";
import "codemirror/addon/display/placeholder.js";
// #endregion

import { codemirror } from "vue-codemirror";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/base16-dark.css";
import "codemirror/mode/clike/clike.js";
export default {
  data() {
    return {
      templateExpandRowkey: [],
      options: [],
      codeExpand: false,
      OptionCodeInput: {
        // codemirror options
        tabSize: 4,
        mode: "text/x-csharp",
        lineNumbers: true,
        theme: "base16-dark",
        line: true,
        placeholder: `请输入模板内容`, // 设置提示文本
      }, //codeMirror配置项

      templateDetail: {
        templateName: "", //内容详情的的title
        templateContent: "", //模板代码内容
        templateId: "", //模板代码的ID
      }, //内容详情显示
      dialogAddOrEditName: "", //模板分类修改或新增的title
      templateDialogAddOrEditName: "", //代码模板修改或新增的title
      inputTempleteClassValue: "", //模板分类查询
      inputTempleteValue: "", //模板名称查询
      updatedTemlateClass: {
        Id: 0,
        TemplateName: "",
      }, //待修改的分类信息
      updatedTemlateId: "", //待修改的模板Id
      classDialogModel: {
        categoryName: "",
      },
      templateDialogModel: {
        categoryId: "",
        templateName: "",
        descriptions: "",
      },
      tableData: [],
      currentPage: 1, // 当前页码，默认为第一页
      pageSize: 20, // 每页显示条数，默认为20条
      totalTableDataSum: 0, // 表格数据总数
      loading: false,
      classAddOrEditDialogVisible: false, //新增模板分类Dialog
      templateAddOrEditDialogVisible: false, //新增模板分类Dialog
      templateContentDialogVisible: false, //模板内容详情Dialog
      searchConditionLast: {
        id: 0,
        pageSize: 20,
        currentPage: 1,
        templateName: "",
        templateClassName: "",
      }, //上次的查询条件
    };
  },
  methods: {
    templateRowkey(row) {
      return String(row.Id);
    },
    selectTemplateClass() {
      this.loading = true;
      let param = {
        id: this.inputTempleteClassValue,
        pageSize: this.pageSize,
        currentPage: this.currentPage,
        templateName: this.inputTempleteValue,
      };

      let isDifferent = false;
      for (let key in param) {
        if (
          key !== "currentPage" &&
          JSON.stringify(param[key]) !==
            JSON.stringify(this.searchConditionLast[key])
        ) {
          isDifferent = true;
          break;
        }
      }

      if (isDifferent) {
        this.currentPage = 1;
        param.currentPage = 1;
      }

      this.searchConditionLast = param;
      this.templateExpandRowkey = [];
      $http
        .post("/CodeTemplate/GetTemplate", param)
        .then((res) => {
          if (res.Data && res.Data.pageData) {
            this.options = res.Data.searchData;
            this.tableData = res.Data.pageData;
            this.totalTableDataSum = res.Data.totalCount;
            //如果模糊搜索不为空，那么自动展开模板分类项
            if (this.inputTempleteValue) {
              this.tableData.forEach((item) => {
                this.templateExpandRowkey.push(String(item.Id));
              });
            }
            this.loading = false;
          } else {
            this.tableData = [];
            this.loading = false;
          }
        })
        .catch((error) => {
          this.$message({
            type: "error",
            message: `数据查询失败,${error}`,
          });
          this.tableData = [];
          this.loading = false;
        });
    }, //查找表格数据

    addTempleteClass() {
      this.dialogAddOrEditName = "添加模板分类";
      this.classAddOrEditDialogVisible = true;
    }, //添加分类button

    confirmTempleteClassAddOrEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogAddOrEditName != "修改模板分类") {
            $http
              .post(`/CodeTemplate/AddTemplateClass`, {
                TemplateName: this.classDialogModel.categoryName,
                Id: 0,
              })
              .then((res) => {
                if (res.Data) {
                  this.$message({
                    message: "新增模板分类成功！",
                    type: "success",
                  });
                  this.classAddOrEditDialogVisible = false;

                  this.classDialogModel.categoryName = "";
                  // 跳转到最后一页
                  this.totalTableDataSum = this.totalTableDataSum + 1;
                  const lastPage = Math.ceil(
                    this.totalTableDataSum / this.pageSize
                  );
                  this.currentPage = lastPage;

                  this.selectTemplateClass();
                } else {
                  this.$message({
                    message: res.Message,
                    type: "error",
                  });
                }
              })
              .catch((error) => {
                this.$message({
                  type: "error",
                  message: `新增模板分类失败！,${error}`,
                });
              });
          } else {
            let param = {
              Id: this.updatedTemlateClass.Id,
              TemplateName: this.classDialogModel.categoryName,
            };
            $http
              .post(`/CodeTemplate/UpdateTemplateClass`, param)
              .then((res) => {
                if (res.Data) {
                  this.$message({
                    message: "修改成功！",
                    type: "success",
                  });
                  this.classAddOrEditDialogVisible = false;

                  this.classDialogModel.categoryName = "";
                  this.selectTemplateClass();
                } else {
                  this.$message({
                    message: res.Message,
                    type: "error",
                  });
                }
              })
              .catch((error) => {
                this.$message({
                  type: "error",
                  message: `修改失败！,${error}`,
                });
              });
          }
        } else {
          return false;
        }
      });
    }, //修改或者新增模板分类

    confirmTempleteAddOrEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.templateDialogAddOrEditName == "添加代码模板") {
            let param = {
              Id: 0,
              CodeTemplateName: this.templateDialogModel.templateName,
              TemplateClassId: this.templateDialogModel.categoryId,
              Description: this.templateDialogModel.descriptions,
            };
            $http
              .post(`/CodeTemplate/AddCodeTemplate`, param)
              .then((res) => {
                if (res.Data) {
                  this.$message({
                    message: "新增模板成功！",
                    type: "success",
                  });
                  this.templateAddOrEditDialogVisible = false;

                  this.templateDialogModel = {
                    categoryId: "",
                    templateName: "",
                    descriptions: "",
                  };

                  const parentItem = this.tableData.find(
                    (item) =>
                      item.Id.toString() == param.TemplateClassId.toString()
                  );

                  // 如果找到了父项
                  if (parentItem) {
                    let result = {
                      ...res.Data,
                      Id: res.Data.ID,
                      ParentId: res.Data.TemplateClassID,
                    };
                    parentItem.Children.push(result);
                  }

                  console.log(this.tableData);
                } else {
                  this.$message({
                    message: res.Message,
                    type: "error",
                  });
                }
              })
              .catch((error) => {
                this.$message({
                  type: "error",
                  message: `新增模板分类失败！,${error}`,
                });
              });
          } else {
            let param = {
              Id: this.updatedTemlateId,
              CodeTemplateName: this.templateDialogModel.templateName,
              TemplateClassId: this.templateDialogModel.categoryId,
              Description: this.templateDialogModel.descriptions,
            };
            $http
              .post(`/CodeTemplate/UpdateCodeTemplate`, param)
              .then((res) => {
                if (res.Data) {
                  // 查找满足条件的对象
                  const targetObject = this.tableData.find((item) => {
                    if (item.Children.length > 0) {
                      return item.Children.find(
                        (child) => child.Id.toString() === param.Id
                      );
                    }
                  });
                  // 修改找到的对象的内容
                  if (targetObject) {
                    targetObject.Children.forEach((child) => {
                      if (child.Id.toString() == param.Id) {
                        // 修改内容
                        child.TemplateName = param.CodeTemplateName;
                        child.Description = param.Description;
                      }
                    });
                  }

                  this.templateAddOrEditDialogVisible = false;

                  this.$message({
                    message: "修改模板信息成功！",
                    type: "success",
                  });

                  this.templateDialogModel = {
                    categoryId: "",
                    templateName: "",
                    descriptions: "",
                  };
                } else {
                  this.$message({
                    message: res.Message,
                    type: "error",
                  });
                }
              })
              .catch((error) => {
                this.$message({
                  type: "error",
                  message: `修改失败！,${error}`,
                });
              });
          }
        } else {
          return false;
        }
      });
    }, //修改或者新增模板

    handleSizeChange(val) {
      this.pageSize = val;
      this.selectTemplateClass();
    }, //页面大小改变

    handleCurrentChange(val) {
      this.pageNum = val;
      this.selectTemplateClass();
    }, //当前页大小改变

    /***********模板分类表格操作 */
    handleAdd(index, row) {
      console.log(index, row);
      this.templateDialogAddOrEditName = "添加代码模板";
      this.templateAddOrEditDialogVisible = true;
      this.templateDialogModel.categoryId = row.Id.toString();
    }, //指定分类下模板新增

    handleEdit(index, row) {
      (this.updatedTemlateClass = {
        Id: row.Id,
        TemplateName: row.TemplateName,
      }), //待修改的分类信息
        //console.log(index, row);
        (this.classAddOrEditDialogVisible = true);
      this.classDialogModel.categoryName = row.TemplateName;
      this.dialogAddOrEditName = "修改模板分类";
    }, //模板分类编辑

    handleDelete(index, row) {
      this.$confirm("确定删除该模板分类？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        $http
          .get(`/CodeTemplate/DeleteTemplateClass?Id=${row.Id}`)
          .then((res) => {
            if (res.Data) {
              this.$message({
                message: "删除成功！",
                type: "success",
              });
              this.currentPage = 1;
              this.selectTemplateClass();
            } else {
              this.$message({
                message: res.Message,
                type: "error",
              });
            }
          })
          .catch((error) => {
            this.$message({
              type: "error",
              message: `删除失败！,${error}`,
            });
          });
      });
    }, //模板分类删除
    /***********模板分类表格操作 */

    /***********代码模板表格操作 */
    handleTemplateDetail(index, row) {
      this.templateDetail = {
        templateContent: row.Content,
        templateId: row.Id,
        templateName: row.TemplateName,
      };

      this.templateContentDialogVisible = true;
    }, //代码模板详情

    confirmSaveTemplateContent() {
      if (this.templateDetail.templateContent == "") {
        return this.$message({
          message: "保存失败！模板内容不可为空！",
          type: "error",
        });
      }
      let param = {
        Id: this.templateDetail.templateId,
        CodeTemplateContent: this.templateDetail.templateContent,
      };
      $http
        .post(`/CodeTemplate/SaveCodeTemplateContent`, param)
        .then((res) => {
          if (res.Data) {
            this.$message({
              message: "保存成功！",
              type: "success",
            });

            this.templateContentDialogVisible = false;

            // 查找满足条件的对象
            const targetObject = this.tableData.find((item) => {
              if (item.Children.length > 0) {
                return item.Children.find(
                  (child) => child.Id.toString() == param.Id
                );
              }
            });

            // 修改找到的对象的内容
            if (targetObject) {
              targetObject.Children.forEach((child) => {
                if (child.Id.toString() == param.Id) {
                  // 修改内容
                  child.Content = param.CodeTemplateContent;
                }
              });
            }
          } else {
            this.$message({
              message: res.Message,
              type: "error",
            });
          }
        })
        .catch((error) => {
          this.$message({
            type: "error",
            message: `保存失败！${error}`,
          });
        });
    }, //确认保存代码模板

    handleTemplateEdit(index, row) {
      console.log(index, row);
      this.updatedTemlateId = row.Id.toString();
      this.templateDialogAddOrEditName = "修改代码模板";
      (this.templateDialogModel = {
        categoryId: row.ParentId.toString(),
        templateName: row.TemplateName,
        descriptions: row.Description,
      }),
        (this.templateAddOrEditDialogVisible = true);
    }, //代码模板编辑

    handleTemplateDelete(index, row) {
      console.log(index, row);
      this.$confirm("确定删除该模板？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        $http
          .get(`/CodeTemplate/DeleteCodeTemplate?Id=${row.Id}`)
          .then((res) => {
            if (res.Data) {
              this.$message({
                message: "删除成功！",
                type: "success",
              });
              const parentItem = this.tableData.find(
                (item) => item.Id.toString() == row.ParentId.toString()
              );
              // 如果找到了父项
              if (parentItem) {
                // 查找子项的索引
                const childIndex = parentItem.Children.findIndex(
                  (child) => child.Id.toString() === row.Id.toString()
                );

                // 如果找到了子项
                if (childIndex !== -1) {
                  // 删除子项
                  parentItem.Children.splice(childIndex, 1);
                }
              }
            } else {
              this.$message({
                message: res.Message,
                type: "error",
              });
            }
          })
          .catch((error) => {
            this.$message({
              type: "error",
              message: `删除失败！,${error}`,
            });
          });
      });
    }, //代码模板删除

    /***********代码模板表格操作 */

    getRowClass(row, index) {
      if (row.row.Children.length == 0) {
        return "row-expand-cover";
      }
    }, //控制展开，即改行没有子元素时，添加row-expand-cover类，该类屏蔽展开

    table_index(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    }, //翻页序号连续
  },
  created() {},
  mounted() {
    this.selectTemplateClass();
  },
};
</script>
<style scope>
.row-expand-cover .el-table__expand-column .el-icon {
  visibility: hidden;
}

.row-expand-cover .el-table__expand-column {
  pointer-events: none;
}
/* @import url(); 引入css类 */
/* @import url(); 引入css类 */
.editor {
  width: 600px;
  height: 800px;
}

.CodeMirror {
  height: 600px;
}
</style>